package com.xiaoxiao.spring.web;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Handler {

	private Method method;

	private Object target;

	private String [] parameters;

	public Handler(Object target,Method method,String [] parameters){
		this.method = method;
		this.target =target;
		this.parameters = parameters;
	}

	public Object doHandler(HttpServletRequest request){
		Object[] args = setParameters(request);
		try {
			return method.invoke(target,args);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

	private Object [] setParameters(HttpServletRequest request) {
		Object [] args = null;
		if(this.parameters!=null&&parameters.length>0){
			args = new Object[parameters.length];
			for (int i = 0; i < this.parameters.length; i++) {
				args[i] = request.getParameter(parameters[i]);
			}
		}
		return args;
	}


}
